
import htmlparse from '@/common/html-parser.js'; 
import {
	uniUploadFile
} from '@/common/promise.js';

// 获取页面栈 delta = n-1
const getCurrenPage = (n) => { 
	let pages = getCurrentPages();	
	let targetPage = pages[pages.length-n];  
	return targetPage;
};

// 解析html 转 数组
const htmlParse = (html) =>{
	let htmlNodes = [];
	let htmlString='';
	
	htmlString = html.replace(/<p([\s\w"=\/\.:;]+)((?:(style="[^"]+")))/ig, '<p')
				.replace(/<p([\s\w"=\/\.:;]+)((?:(class="[^"]+")))/ig, '<p')
				.replace(/<p>/ig, '<p class="html_p">')
				.replace(/<br>/ig, '<p class="html_p">')
				.replace(/<div>/ig, '<div class="html_p">')
				.replace(/<img/ig, '<img class="html_img"');
				// .replace(/<img([\s\w"-=\/\.:;]+)((?:(height="[^"]+")))/ig, '<img$1')
				// .replace(/<img([\s\w"-=\/\.:;]+)((?:(width="[^"]+")))/ig, '<img$1')
				// .replace(/<img([\s\w"-=\/\.:;]+)((?:(style="[^"]+")))/ig, '<img$1')
				// .replace(/<img([\s\w"-=\/\.:;]+)((?:(alt="[^"]+")))/ig, '<img$1')
				// .replace(/<img([\s\w"-=\/\.:;]+)/ig, '<img$1 class="html_img"')
			   
	htmlNodes = htmlparse(htmlString);  	
	return htmlNodes;
};

/*  
* 参数复杂路由跳转传入（object）
* opentype:'navigate',   跳转方式 跟opentype
* backOpenType:'navigate', 回跳方式
* url:'/pages/member/group/group',     // 目标url
* backurl:'',       返回路由
* params:{type:'select',memberid:this.member.select},  	  // 目标url参数 * 
* backparams:{type:'select',memberid:[]},   返回路由参数
*   
*  /pages/login/login?id=1&type=add&backurl=%%%%%%%%%%%%5
*/
const router = (data) =>{   
	let targetUrl='',
		url='',
		urlQuery='',
		params='',
		backUrl='',
		backUrlParams='',
		urlParams='', // eg 'pages/login/login?type=a' 
		backOpenType='';
	
	// 处理目标url
	// 1 判断是否带url参数
	if(data.url.indexOf('?')!=-1){
		data.url=data.url.split('?');
		url=data.url[0];
		urlQuery=data.url[1]; 
		params=urlQuery; 
	}else{
		url=data.url;
	}
	
	// 处理参数
	if(data.params){ 
		for(let i in data.params){
			if(typeof(data.params[i])=='object'){ // 处理参数值为对象时转码
				data.params[i]=objectToEncode(data.params[i]); 
			}
		}		 
		if(urlQuery){
			params=urlQuery+'&'+jsonToQuery(data.params);
		}else{
			params=jsonToQuery(data.params);
		} 
	} 

	if(data.backurl){		
		if(data.backOpenType){
			backOpenType="&backOpenType="+data.backOpenType; 
		}
		// 回传参数
		//1 判断url是否带参数   /pages/login/login?a=1&b=2
		if(data.backurl.indexOf('?')!=-1){
			data.backurl=data.backurl.split('?');
			backUrl=data.backurl[0]; 
			urlParams=data.backurl[1];
			backUrlParams=urlParams;
		}else{
			backUrl=data.backurl;
		}  
		
		if(params){
			backUrl="&backurl="+backUrl; 
		}else{
			backUrl="?backurl="+backUrl; 
		} 
		
		if(data.backparams){ 
			if(backUrlParams){
				backUrlParams=backUrlParams+'&'+jsonToQuery(data.backparams);
			}else{
				backUrlParams=jsonToQuery(data.backparams);
			}  
		} 
		if(backUrlParams){
			backUrlParams="&backparams="+objectToEncode(backUrlParams); 
		} 
	}

	targetUrl=url+'?'+params+backUrl+backUrlParams+backOpenType;  
	switch(data.opentype){
		case 'navigate':  
			uni.navigateTo({
				url: targetUrl,
			}); 
		break;
		case 'redirect':
			uni.redirectTo({
				url: targetUrl,
			});
		break;
		case 'switchTab':
			uni.redirectTo({
				url: targetUrl,
			});
		break;
		case 'reLaunch':
			uni.reLaunch({
				url: targetUrl,
			});
		break; 
	}
};

 

/*
 * 字符串转码
 * "xxxxx"=>%7B%22id%22%3A1%7D
 * */
const queryToEncode = (data) =>{ 
	let enCode=encodeURIComponent(data);   
	return enCode; 
};

/*
 * 字符串解码
 * %7B%22id%22%3A1%7D=>"xxxxx"
 * */
const encodeToString = (data) =>{ 
	let str=decodeURIComponent(data);  
	return str; 
};

/*
 * 	url参数转对象  
 * 	eg: type=2&ca_id=1  => {type:2,ca_id:1}
 * 		[type=2,ca_id=1] => [[type,2],[ca_id,1]] =>	{type:2,ca_id:1}
 * */
const queryToJSON = (str) =>{
	let query=[],
		data={};	
	let query_arr=str.split('&');
	query_arr.forEach(item=>{
		let query_item = item.split('=');
		query.push(query_item);		
	});	
	query.forEach(item=>{
		data[item[0]]=item[1];
	});
	return data;  
};

/*
 * json转化成url参数
 *  eg:{a:1,b:2} =  a=1&b=2
 * 
 * ***/ 
const jsonToQuery = (data) =>{	
	let jsonStr=JSON.stringify(data);	
	let query='';
	let reg1=/[{}"]/ig; // 去掉{}"
	let reg2=/[:]/ig; // 匹配全部:
	let reg3=/[,]/ig;	 // 匹配全部,
		query=jsonStr.replace(reg1,"") // 去掉{}"
			.replace(reg2,"=") // =替换:
			.replace(reg3,"&"); // &替换,          
	return query;
};


// 检查手机号 
const checkPhone = (data) => {
	let phoneReg = /^1[2|3|4|5|6|7|8|9][0-9]{9}$/;  	
	if(!phoneReg.test(data)){ 
		return false;
	}else{
		// console.log('手机格式正确')
		return true;
	}
}; 

// 检测身份证号等
const checkIdCard = (data) => {	 
	let cardReg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
	if(!cardReg.test(data)){
		// console.log('错误')
		return false;
	}else{
		// console.log('手机格式正确')
		return true;
	} 
};

// 替换字符串指定位置* （手机号/身份证号）
const replaceStr = (str,index,changeStr) => {	  
	return str.substr(0, index) + changeStr+ str.substr(index + changeStr.length); 
};

// 阻止按钮快速点击事件
const stop=function stopClickEvent(fn){
    let that = this; 
    if (that.isStop) {
        that.isStop = false;
        fn(); 
    } else {
    	//如果一直走else分支可能是你没有在页面的data下面挂载onoff:true,不然一直都会走else
        console.log("请稍后点击");
    }
};

/*
*  
* count:最多上传图片数量，最多9张
* len:已上传数量
* success:成功回调
* 
* */
const uploadImage=(data)=>{  
	let _this = this;
	let imgUrl=[],
		uploadNum=data.length,
		count=data.maxSize, 
		callback=data.success; 
			
	if(count>9){
		count=9;
	}else{
		count=count-uploadNum; // 计算剩余可上传数量
	} 
	 
	uni.chooseImage({
	    count: count, //默认9
	    sizeType: ['original','compressed'], //可以指定是原图还是压缩图，默认二者都有
	    sourceType: ['album','camera'], //从相册选择
	    success: function (res){   
			return callback(res.tempFilePaths); 
	    }
	});
};


/*
*  预览图片
*  data.data  预览图片 数组
*  data.index 第几张开始预览
* */
const previewImage=(data)=>{	
	let img=data.data,
		index=data.index;
	uni.previewImage({
		current:index,
		urls:img,
		loop:true,
		success(res) {
			console.log('previewImg-success',res);
		},
		fail(err) {
			console.log('previewImg-err',err);
		}
	});
};

/*
 *  上传文件到服务器 
 *  data.url 服务器接口
 *  data.filePath 图片本地临时地址
 *  data.name 目录名称
 *  data.formData 其他参数
 * 
 * */
const uploadToServe = (data) => {   
	let callback = data.success;
	return new Promise((resolve, reject) => {
		uniUploadFile({
			type:data.type,
			url: data.url,
			filePath: data.filePath,
			name: data.name,
			formData: data.formData
		}).then((up_res) => {     
			if(up_res.statusCode==200){
				let up_res_data = decodeURIComponent(up_res.data);
				up_res_data = up_res_data.replace(/[\\]/g, '');
				up_res_data = JSON.parse(up_res_data);
				
				resolve(up_res_data);
			}
		}).catch((err) => { 
			reject(err);
		});
	});
}; 

// 坐标转换 度分秒格式
const d2Dms = (data) => {
  let d = parseInt(data);
  let m = parseInt((data - d) * 60);
  let s = Math.floor(((data - d) * 60 - m) * 60 * 100) / 100;
  return d + "°" + m + "′" + s + "″";
}
 

 


export {
	getCurrenPage,
	htmlParse,
	router, 
	checkPhone,
	stop,
	checkIdCard,
	queryToEncode,
	queryToJSON,
	encodeToString,
	uploadImage,
	previewImage,
	jsonToQuery,
	replaceStr,
	uploadToServe,
	d2Dms
}; 






